import { defineStore } from "pinia";

import { ADMIN_LOGIN_TIME_KEY, ADMIN_TOKEN_KEY } from "@/config/constants";

export const useAdminStore = defineStore("admin", {
    state: () => ({
        userinfo: {
            id: 0,
            username: "",
            avatar: "",
            nickname: "",
            email: ""
        },
        token: localStorage.getItem(ADMIN_TOKEN_KEY) || "",
        loginTime: localStorage.getItem(ADMIN_LOGIN_TIME_KEY) || "",
        initialized: false // 是否已经初始化过用户信息。避免 HMR 时，重复初始化用户信息
    }),
    getters: {
        isLogin: state => !!state.token
    },
    actions: {
        async register(username: string, password: string, email: string) {
            // // 模拟注册
            // const res = await new Promise(resolve => setTimeout(resolve, 1000));
            // return res;
            return await Apis.AdminLogin.register({
                data: { username, password, email}
            });
        },
        async login(username: string, password: string) {
            // // 模拟登录
            // const res = await new Promise(resolve => setTimeout(resolve, 1000));
            // // 登录成功，保存用户信息
            // this.userinfo = {
            //     username: "admin",
            //     avatar: "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
            //     nickname: "管理员",
            //     email: ""
            // };

            const res = await Apis.AdminLogin.loginByAccount({
                data: {
                    username,
                    password,
                    terminal: "pc"
                }
            });
            this.userinfo = res.data;
            this.token = res.data.token;
            this.loginTime = Date.now() + "";
            localStorage.setItem(ADMIN_TOKEN_KEY, this.token);
            localStorage.setItem(ADMIN_LOGIN_TIME_KEY, this.loginTime);
            return res;
        },
        async logout() {
            this.clearUserInfo();
        },
        setUserInfo(userinfo: any) {
            this.userinfo = userinfo;
        },
        clearUserInfo() {
            this.userinfo = {} as any;
            localStorage.removeItem(ADMIN_TOKEN_KEY);
            localStorage.removeItem(ADMIN_LOGIN_TIME_KEY);
        },
        /**
         * 尝试恢复用户登录状态到内存中
         */
        async tryRestoreUser() {
            if (this.initialized) return true;
            const token = localStorage.getItem(ADMIN_TOKEN_KEY);
            if (!token) return false;

            try {
                // const response = await fetch(import.meta.env.VITE_API_BASE_URL + "/api/user/info");
                // const res = await response.json();
                // const res = await Apis.User.findSelfInfo();
                const res = await Apis.SysUser.findSelfUserInfo({});

                if (res.code < 200 || res.code > 300) throw new Error(res.msg);

                this.userinfo = res.data;
                this.token = token;
                this.loginTime = Date.now() + "";
                localStorage.setItem(ADMIN_LOGIN_TIME_KEY, this.loginTime);
                return true;
            } catch (error) {
                // 只有出错，就清空登录相关信息
                this.clearUserInfo();
                return false;
            }
        }
    }
});
